package com.ccp.dev.workflow.service.bpm.impl;

import com.ccp.dev.core.basic.engine.GroovyScriptEngine;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.system.model.SysUser;
import com.ccp.dev.system.service.SysUserService;
import com.ccp.dev.workflow.bpmconst.BpmConst;
import com.ccp.dev.workflow.model.BpmNodeUser;
import com.ccp.dev.workflow.model.bpm.CalcVars;
import com.ccp.dev.workflow.model.bpm.PreViewModel;
import com.ccp.dev.workflow.model.bpm.TaskExecutor;
import com.ccp.dev.workflow.service.bpm.BpmNodeUserUtil;
import com.ccp.dev.workflow.service.bpm.IBpmNodeUserCalculation;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * 根据节点用户设置为“人员脚本”
 * 
 * @author fanruiqi
 */
@Component
public class BpmNodeUserCalculationPersonScript implements IBpmNodeUserCalculation {
	@Resource
	private SysUserService sysUserService;
	@Resource
	private GroovyScriptEngine groovyScriptEngine;
	
	@Override
	public List<SysUser> getExecutor(BpmNodeUser bpmNodeUser, CalcVars vars) {
		String prevUserId = vars.getPrevExecUserId();
		String startUserId = vars.getStartUserId();
		
		String script = bpmNodeUser.getCmpIds();
		List<SysUser> users = new ArrayList<SysUser>();
		Map<String, Object> grooVars = new HashMap<String, Object>();
		
		String actInstId="";
		if(StringUtil.isNotEmpty(vars.getProcInstId()) ){
			actInstId=vars.getProcInstId();
		}
		grooVars.put("actInstId", actInstId);
		if(vars.getVars().size()>0){
			grooVars.putAll(vars.getVars());
		}
		
		
		grooVars.put(BpmConst.StartUser, startUserId);
		grooVars.put(BpmConst.PrevUser, prevUserId);
		Object result = groovyScriptEngine.executeObject(script, grooVars);
		if (result == null) {
			return users;
		}
		Set<String> set = (Set<String>) result;
		for (Iterator<String> it = set.iterator(); it.hasNext();) {
			String userId = it.next();
			SysUser sysUser = sysUserService.getById(userId);
			users.add(sysUser);
		}
		return users;
	}

	@Override
	public String getTitle() {
		return "人员脚本";
	}

	@Override
	public Set<TaskExecutor> getTaskExecutor(BpmNodeUser bpmNodeUser, CalcVars vars) {
		int extractUser=bpmNodeUser.getExtractUser();
		
		List<SysUser> sysUsers = this.getExecutor(bpmNodeUser, vars);
		Set<TaskExecutor> uIdSet = BpmNodeUserUtil.getExcutorsByUsers(sysUsers, extractUser);
		return uIdSet;
	
	}

	@Override
	public boolean supportMockModel() {
		
		return true;
	}

	@Override
	public List<PreViewModel> getMockModel(BpmNodeUser bpmNodeUser) {
		List<PreViewModel> list=new ArrayList<PreViewModel>();
		
		PreViewModel startViewModel=new PreViewModel();
		startViewModel.setType(PreViewModel.START_USER);
		list.add(startViewModel);
		
		PreViewModel preViewModel=new PreViewModel();
		preViewModel.setType(PreViewModel.PRE_VIEW_USER);
		list.add(preViewModel);
		
		return list;
	}
	
	@Override
	public boolean supportPreView() {
		return true;
	}


}
